<!-- 车辆维修 0，1，2 待维修 中 完成 -->
<template>
  <div class="page-container">
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />
    <table-index :table="table" @loadData="loadData">
      <template #repairAllAmount="{ record }">
        <span>{{ record.repairAmount ? record.repairAmount : '-' }}</span>
      </template>
      <template #bindOrder="{ record }">
        <div v-if="record.orderNo">
          <div
            ><span @click="() => onLink(record)" v-if="record.orderNo" class="order-line">{{ record.orderNo }}</span>
            <span v-else>-</span>
          </div>
          <div>交车人：{{ record.giveStaffName || '-' }}</div>
        </div>
        <div v-else>-</div>
      </template>
      <template #memberInfo="{ record }">
        <memberInfo :record="record" />
      </template>
    </table-index>
  </div>

  <!-- 导入 -->
  <import-modal ref="imoportRef" action="/repair/importExcel" download-import="carRepair" @ok="loadData" />
</template>

<script setup name="CarRepairList">
  import { getRepairList, getStoreList, repairExport, closeRepair } from '@/api/asset/repair'
  import { useExport } from '@/hooks/list'
  import { onMounted, ref, reactive, computed } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { Modal, Notification } from '@arco-design/web-vue'
  import memberInfo from '@/views/assets/compnoents/memberInfo.vue'
  const imoportRef = ref(null)
  import { usePageDict } from '@/hooks/useDict'
  const repairDict = usePageDict('repairDict')
  import dayjs from 'dayjs'

  import useNavigate from '@/hooks/useNavigate'
  import { useRoute } from 'vue-router'
  const route = useRoute()
  const routeQuery = route.query
  const { navigateTo } = useNavigate()
  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '车牌号', prop: 'licenseNoLike', type: 'a-input', maxlength: 10 },
      {
        label: '车辆当前归属门店',
        prop: 'carSiteIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_site_listBystaff',
        },
      },
      {
        label: '维修状态',
        prop: 'statusList',
        type: 'a-select',
        multiple: true,
        options: repairDict.allStatusMap,
      },
      {
        label: '维修周期',
        prop: 'searchDate',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.timeStart = value[0]
          queryParam.timeEnd = value[1]
        },
      },
      {
        label: '维修单关联门店',
        prop: 'siteIdList',
        type: 'remote-select',
        attrs: {
          type: 'multiple_site_listBystaff',
        },
      },
      { label: '维修单号', prop: 'repairNoLike', type: 'a-input' },
      {
        label: '负责人',
        prop: 'undertakerIdList',
        type: 'remote-select',
        attrs: {
          type: 'staff_authOrg_multiple',
        },
      },
      { label: '车架号', prop: 'vin', type: 'a-input' },
      {
        label: '修理厂',
        prop: 'repairShopId',
        type: 'remote-select',
        attrs: {
          type: 'supplier_list',
          params: {
            status: 1,
            supplierType: 0,
          },
        },
      },
      { label: '关联单号', prop: 'orderNoLike', type: 'a-input', maxlength: 100 },
    ]
  })
  // 接口参数（不包含page信息）
  const queryParam = reactive({
    searchDate: [],
  })

  // table 配置
  const table = useTable({
    queryParam,
    columns: [
      { title: '维修单号', dataIndex: 'repairNo', width: 150, fixed: 'left' },
      { title: '车牌号', dataIndex: 'licenseNo' },
      { title: '车辆当前归属门店', dataIndex: 'carSiteName', width: 150 },
      { title: '维修单关联门店', dataIndex: 'siteName', width: 150 },
      { title: '修理厂', dataIndex: 'repairShop' },
      {
        title: '入厂日期',
        dataIndex: 'arrivalTime',
        width: 170,
        sortable: {
          sorter: true,
          sortDirections: ['ascend', 'descend'],
        },
        render: (record) => {
          if (record.arrivalTime) {
            return dayjs(record.arrivalTime).format('YYYY-MM-DD HH:mm:ss')
          }
        },
      },
      {
        title: '出厂日期',
        dataIndex: 'leaveTime',
        width: 170,
        sortable: {
          sorter: true,
          sortDirections: ['ascend', 'descend'],
        },
        render: (record) => {
          if (record.leaveTime) {
            return dayjs(record.leaveTime).format('YYYY-MM-DD HH:mm:ss')
          }
        },
      },
      { title: '关联单号', dataIndex: 'order', slotName: 'bindOrder', width: 240 },
      { title: '承租人信息', dataIndex: 'memberInfo', slotName: 'memberInfo', width: 120 },
      { title: '费用合计', dataIndex: 'repairAmount', slotName: 'repairAllAmount', unit: '元', width: 110 },
      { title: '维修状态', dataIndex: 'statusStr', width: 100 },
      { title: '负责人', dataIndex: 'undertaker', width: 120 },
    ],
    operates: [
      {
        label: '详情',
        permission: 'svms:asstes:car:car-repair.detail',
        method: (record, column, rowIndex) => {
          console.log(record, column, rowIndex)
          navigateTo(`/car-repair/detail/${record.id}?status=${record.status}`, `${record.licenseNo}-维修详情`)
        },
      },
      {
        label: '费用信息',
        permission: 'svms:asstes:car:car-repair.fee',
        show: (record) => record.status == 2,
        method: (record) => {
          navigateTo(`/car-repair/detail/${record.id}?activeType=${2}&status=${record.status}`, `${record.licenseNo}-费用信息`)
        },
      },
      {
        label: '编辑',
        permission: 'svms:asstes:car:car-repair.edit',
        show: (record) => record.status == 0 || record.status == 1 || record.status == 2,
        method: (record) => {
          // 0 待维修 1 维修中 2 维修完成 7 已关闭
          if (record.status == 2) {
            navigateTo(`/car-repair/start/${record.id + '&finish'}?page=carRepair`, `${record.licenseNo}-维修编辑`)
          } else if (record.status == 1) {
            navigateTo(`/car-repair/start/${record.id + '&start'}?page=carRepair`, `${record.licenseNo}-维修编辑`)
          } else {
            navigateTo(`/car-repair/edit/${record.id}?page=carRepair`, `${record.licenseNo}-维修编辑`)
          }
        },
      },
      {
        label: '开始维修',
        permission: 'svms:asstes:car:car-repair.start',
        show: (record) => record.status == 0,
        method: (record) => {
          navigateTo(`/car-repair/start/${record.id + '&start'}?page=carRepair`, `${record.licenseNo}-开始维修`)
        },
      },
      {
        label: '维修完成',
        permission: 'svms:asstes:car:car-repair.end',
        show: (record) => record.status == 1,
        method: (record) => {
          navigateTo(`/car-repair/start/${record.id + '&end'}?page=carRepair`, `${record.licenseNo}-维修完成`)
        },
      },
      {
        label: '关闭',
        permission: 'svms:asstes:car:car-repair.close',
        show: (record) => record.status == 0 || record.status == 1,
        method: (record) => {
          Modal.confirm({
            title: '关闭维修单',
            cancelText: '取消',
            okText: '确认',
            bodyStyle: {
              'text-align': 'center',
            },
            content: '关闭后，不支持恢复，是否确认关闭？',
            onOk: () => {
              closeRepair({ id: record.id }).then(() => {
                Notification.success({
                  content: '关闭成功',
                  closable: true,
                  duration: 3000,
                })
                loadData()
              })
            },
          })
        },
      },
      {
        label: '操作记录',
        permission: 'svms:asstes:car:car-repair.operaterecords',
        method: (record) => {
          navigateTo(`/car-repair/detail/${record.id}?activeType=${3}&status=${record.status}`, `${record.licenseNo}-操作记录`)
        },
      },
    ],
    buttons: [
      {
        mode: 'import',
        permission: 'svms:asstes:car:car-repair.import',
        label: '导入',
        method: () => {
          imoportRef.value.show()
        },
      },
      {
        mode: 'import',
        permission: 'svms:asstes:car:car-repair.export',
        label: '导出',
        method: () => handleExport(),
      },
      {
        type: 'primary',
        permission: 'svms:asstes:car:car-repair.add',
        mode: 'import',
        icon: 'plus',
        label: '新增',
        method: () => {
          navigateTo('/car-repair/create/create?page=carRepair')
        },
      },
    ],
  })
  // 列表接口调用
  const loadData = (page, type) => {
    if (type === 'reset') {
      if (routeQuery.id) {
        queryParam.statusList = []
        queryParam.statusList.push(Number(routeQuery.id))
      }
    }
    const fn = useFetchTableDataApi(table, queryParam, getRepairList)
    fn(page)
  }
  const onLink = (record) => {
    if (record.orderType == 2) {
      navigateTo(`/short-order/detail/${record.orderId}`, `${record.orderNo}-短租详情`)
    } else if (record.orderType == 3) {
      navigateTo(`/long-order/detail/${record.orderId}`, `${record.orderNo}-长租详情`)
    }
  }

  // 导出事件
  const handleExport = () => {
    useExport(repairExport, queryParam)
  }

  // 门店列表
  const storeList = ref([])
  const getStore = () => {
    getStoreList().then((res) => {
      const result = res.result.map((e) => {
        e.value = e.id
        e.label = e.siteName
        return e
      })
      storeList.value = result
    })
  }

  onMounted(() => {
    if (routeQuery.status) {
      queryParam.statusList = [Number(routeQuery.status)]
    }
    loadData()
    getStore()
  })
</script>

<style lang="less" scoped>
  .order-line {
    color: #165dff;
    font-size: 12px;
    text-decoration: underline;
    cursor: pointer;
  }
</style>
